package com.binaryTree;

import java.util.*;

public class BinaryTreePostorderTraversal0205_145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        postorder(root,res);

        return res;
    }

    private void postorder(TreeNode root, List<Integer> res) {
        if(root == null) return;

        postorder(root.left,res);
        postorder(root.right,res);
        res.add(root.val);
    }
}

class BinaryTreePostorderTraversal{

    // 求：左右中， 过程： 先中右左，到 res，再 res 翻转。
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            if(pop != null) res.add(pop.val);
            else continue;
            stack.push(pop.left);
            stack.push(pop.right);
        }
        Collections.reverse(res);
        return res;
    }
}

class Postorder {

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> sta = new Stack<>();
        if(root != null) sta.push(root);

        while (!sta.isEmpty()){
            TreeNode node = sta.peek();
            if(node != null){
                sta.pop();
                sta.push(node);
                sta.push(null);
                if(node.right != null) sta.push(node.right);
                if(node.left != null) sta.push(node.left);
            }else {
                sta.pop();
                node = sta.pop();
                res.add(node.val);
            }
        }
        return res;
    }
}
